#!/bin/bash

source $DRAW_INI
source $DRAW_CFG

if [ -z $2 ];then
  LTAG=""
  SUFFIX="_genome.readct"
else
  LTAG="-L $2"
  SUFFIX="_target.readct"
fi

if [ -z $STAT_DIR ];then
  OUT="${1}$SUFFIX"
else
	mkdir -p $STAT_DIR
  OUT="$STAT_DIR/${1}$SUFFIX"
fi


java -Xmx2g -jar $GATK \
 -R $REF_FASTA \
 -T CountReads \
 --read_filter MappingQualityUnavailable \
 --read_filter UnmappedRead \
 --read_filter DuplicateRead \
 --read_filter MappingQualityZero \
 $LTAG \
 -I $1.bam > $OUT

EXITSTATUS=$?

if [ ! -s $OUT ]
then
 echo "Incomplete output file $OUT"
 exit 100
fi

if [ $(stat --printf="%s" $OUT) = 100 ];then
 echo "Memory Error. Exitting."
 exit 100
fi

if [ $EXITSTATUS -ne 0 ];then exit $EXITSTATUS;fi
